#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFileDialog>
#include <QDebug>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    // 创建一个菜单栏，里面有两个菜单项，打开和保存
    QMenuBar* menuBar = this->menuBar();

    QMenu* file = new QMenu("文件");
    menuBar->addMenu(file);

    QAction* open = new QAction("打开");
    QAction* save = new QAction("保存");
    file->addAction(open);
    file->addAction(save);

    // 设置一个中心文本框
    text = new QPlainTextEdit(this);
    this->setCentralWidget(text);

    // 给两个菜单项设置两个槽函数用于文件读写
    connect(open, &QAction::triggered, this, &MainWindow::handle1);
    connect(save, &QAction::triggered, this, &MainWindow::handle2);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::handle1()
{
    // 用于打开文件，将文件中的数据读到文本框中
    QString filepath = QFileDialog::getOpenFileName();

    QFile f(filepath);
    if(!f.open(QFile::ReadOnly))
    {
        qDebug() << "打开文件失败：" << filepath;
        return;
    }

    // 将打开的文件显示到状态栏上
    QStatusBar* statusBar = this->statusBar();
    statusBar->showMessage(filepath);

    QString content = f.readAll();
    f.close();

    text->setPlainText(content);
}

void MainWindow::handle2()
{
    //
    QString filepath = QFileDialog::getSaveFileName();

    QFile f(filepath);
    if(!f.open(QFile::WriteOnly))
    {
        qDebug() << "打开文件失败：" << filepath;
        return;
    }

    // 将打开的文件显示到状态栏上
    QStatusBar* statusBar = this->statusBar();
    statusBar->showMessage(filepath);

    f.write(text->toPlainText().toUtf8());

    f.close();
}

